package com.mew.chess.core.common.handler;

import com.mew.chess.core.common.message.request.GiftRequestMessage;
import com.mew.chess.core.common.provide.UserFeignService;
import com.mew.common.enm.GoldProcessType;
import com.mew.common.exception.ResponseCode;
import com.mew.common.rest.LongMessage;
import com.mew.common.rest.bo.GameSession;
import com.zebra.remoting.protocol.ZebraCommand;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Data
@Slf4j
public abstract class GiftHandler  implements ChessPlayHandler<GiftRequestMessage>{

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handle(ZebraCommand<GiftRequestMessage> command, GameSession gameSession) {
        long userId = gameSession.getUserId();
        int roomId = gameSession.getRoomId();
        int tableId = gameSession.getTableId();
        int giftType = command.getRequest().getGiftType();
        int giftIdx = command.getRequest().getGiftIdx();

        long giftGold = getGiftGold(giftType,giftIdx);
        //验证
        int status = commonValid(gameSession,giftGold);
        if(status != ResponseCode.Success.code()){
            command.sendFailureCode(status);
            return ;
        }
        //收取送礼的钱
        userFeignService.addGold(userId, -giftGold, GoldProcessType.GameGift.code());
        gameSession.updateGoldNumber(-giftGold);
        //这里修改 送礼的钱从本地缓存的钱里扣 ， 因为压注阶段会改变玩家余额 。但是赔付前redis不会扣除压注钱
        command.sendMessage(LongMessage.builder().l(gameSession.getGoldNumber()).build());

        List<GameSession> sessions = getSessions(roomId,tableId);
        GiftRequestMessage message = command.getRequest();
        message.setUserId(command.getUserId());
        ChessPushMessageUtil.broadcastMessage(sessions,ChessHandlerMapCmdType.Gift.cmd(),message);
        log.info("-- gift : user:{}  giftType:{}  giftIdx:{}  giftGold:{}",gameSession,giftType,giftIdx,giftGold);
    }

    /**
     * 公共验证
     * @param gameSession
     * @param giftGold
     * @return
     */
    public int commonValid(GameSession gameSession,long giftGold){
        //礼物金币配置不对
        if(giftGold <= 0){
            return ResponseCode.ParamInvalid.code();
        }
        //钱不够
        if(gameSession.getGoldNumber() < giftGold){
            return ResponseCode.GoldNo.code();
        }
        return ResponseCode.Success.code();
    }
    public abstract long getGiftGold(int type, int idx);
    public abstract List<GameSession> getSessions(int roomId,int tableId);
}
